<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\model\AgentChannel;
use app\model\MobileSupplier;
use think\Request;

class MobileStatistic extends Controller
{
    /**
     * @api {GET} /admin/mobileStatistic 话费成功率
     * @apiName mobileStaticIndex 话费成功率
     * @apiDescription  话费成功率统计
     * @apiParam {String=supplier,agentChannel} list_type 类型 supplier：供应商话费成功率 agentChannel：代理渠道充值成功率
     * @apiParam {String} dateymd[start] 统计开始时间
     * @apiParam {String} dateymd[end] 统计结束时间
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiGroup Admin2_0
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        if (!$request->has('list_type')) {
            return fail('缺少必要参数');
        }

        return $this->{$request->param('list_type')}($request);
    }

    /**
     * @api {GET} /admin/mobileStatistic/supplier 供应商话费成功率
     * @apiName mobileStaticSupplier 供应商话费成功率
     * @apiDescription  供应商话费成功率统计
     * @apiParam {String} dateymd[start] 统计开始时间
     * @apiParam {String} dateymd[end] 统计结束时间
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiGroup Admin2_0
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function supplier(Request $request)
    {
        $dateYmd = $request->only(['dateymd' => ['start' => date('Y-m-d'), 'end' => date('Y-m-d')]]);
        if (empty($dateYmd['dateymd']['start'])) {
            $dateYmd['dateymd']['start'] = date('Y-m-d');
        }
        if (empty($dateYmd['dateymd']['end'])) {
            $dateYmd['dateymd']['end'] = date('Y-m-d');
        }

        $data = MobileSupplier::withTrashed()->alias('MobileSupplier') // withTrashed 时候 需要alias为类名 MobileSupplier 否则关联失败
                ->field(['MobileSupplier.id', 'MobileSupplier.name'])
                ->hasWhere('successStatics', function ($query) use ($dateYmd) {
                    $query->whereBetween('dateymd', array_values($dateYmd['dateymd']));
                })->with(['successStatics' => function ($query) use ($dateYmd) {
                    $query->fieldRaw('supplier_id,goods_type,sum(success) as success,sum(fail) as fail,sum(cost_time) as cost_time')
                        ->whereBetween('dateymd', array_values($dateYmd['dateymd']))
                        ->group('supplier_id,goods_type');
                }, 'ispStatics' => function ($query) use ($dateYmd) {
                    $query->fieldRaw('supplier_id,isp_type,sum(success) as success,sum(fail) as fail,sum(cost_time) as cost_time')
                    ->whereBetween('dateymd', array_values($dateYmd['dateymd']))
                    ->group('supplier_id,isp_type');
                }])->paginate($this->getPaginate())->toArray();

        // 处理成功 失败 总数的汇总
        foreach ($data['data'] as $k => $v) {
            // step 快慢充
            $data['data'][$k]['goods_type'] = [];
            $data['data'][$k]['isp_type'] = [];
            if ($v['successStatics']) {
                foreach ($v['successStatics'] as $k2 => $v2) {
                    $v2['all_num'] = $v2['fail'] + $v2['success'];
                    if (1 == $v2['goods_type']) {  // 慢充
                        $data['data'][$k]['goods_type']['supplier_slow'] = $v2;
                    } else {
                        $data['data'][$k]['goods_type']['supplier_fast'] = $v2;
                    }
                    if (!isset($data['data'][$k]['goods_type']['supplier_all'])) {
                        $data['data'][$k]['goods_type']['supplier_all'] = [
                            'all_num' => $v2['all_num'],
                            'fail' => $v2['fail'],
                            'cost_time' => $v2['cost_time'],
                            'success' => $v2['success'],
                        ];
                    } else {
                        $data['data'][$k]['goods_type']['supplier_all']['all_num'] += $v2['all_num'];
                        $data['data'][$k]['goods_type']['supplier_all']['fail'] += $v2['fail'];
                        $data['data'][$k]['goods_type']['supplier_all']['success'] += $v2['success'];
                        $data['data'][$k]['goods_type']['supplier_all']['cost_time'] += $v2['cost_time'];
                    }
                }
            }
            unset($data['data'][$k]['successStatics']);

            // 运营商
            if ($v['ispStatics']) {
                foreach ($v['ispStatics'] as $k2 => $v2) {
                    $v2['all_num'] = $v2['fail'] + $v2['success'];
                    // 运营商统计
                    if (1 == $v2['isp_type']) {
                        $data['data'][$k]['isp_type']['isp_yd'] = $v2;
                    } elseif (2 == $v2['isp_type']) {
                        $data['data'][$k]['isp_type']['isp_lt'] = $v2;
                    } elseif (3 == $v2['isp_type']) {
                        $data['data'][$k]['isp_type']['isp_dx'] = $v2;
                    } else {
                        $data['data'][$k]['isp_type']['unknow'] = $v2;
                    }
                }
            }
            unset($data['data'][$k]['ispStatics']);
        }

        return success('', $data);
    }

    /**
     * @api {GET} /admin/mobileStatistic/agentChannel 代理渠道充值成功率
     * @apiName mobileStaticAgentChannel 代理渠道充值成功率
     * @apiDescription  代理渠道充值成功率
     * @apiParam {String} dateymd[start] 统计开始时间
     * @apiParam {String} dateymd[end] 统计结束时间
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiGroup Admin2_0
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function agentChannel(Request $request)
    {
        $dateYmd = $request->only(['dateymd' => ['start' => date('Y-m-d'), 'end' => date('Y-m-d')]]);
        if (empty($dateYmd['start'])) {
            $dateYmd['start'] = date('Y-m-d');
        }
        if (empty($dateYmd['end'])) {
            $dateYmd['end'] = date('Y-m-d');
        }
        $data = AgentChannel::withTrashed()
            ->field(['id', 'name', 'agent_id'])
            ->withJoin(['agent' => function ($query) {
                $query->withField(['id', 'company_name' => 'company_name', 'username' => 'username']);
            }])->with(['successStatics' => function ($query) use ($dateYmd) {
                $query->fieldRaw('channel_id,goods_type,sum(success) as success,sum(fail) as fail')
                    ->whereBetween('dateymd', array_values($dateYmd['dateymd']))->whereNotNull('id')
                    ->group('channel_id,goods_type');
            }])
            ->paginate($this->getPaginate())->toArray();

        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['orders'] = [];
            if ($v['successStatics']) {
                foreach ($v['successStatics'] as $k2 => $v2) {
                    $v2['all_num'] = $v2['fail'] + $v2['success'];
                    if (1 == $v2['goods_type']) {
                        $data['data'][$k]['orders']['channel_slow'] = $v2;
                    } else {
                        $data['data'][$k]['orders']['channel_fast'] = $v2;
                    }
                    if (!isset($data['data'][$k]['orders']['channel_all'])) {
                        $data['data'][$k]['orders']['channel_all']['success'] = $v2['success'];
                        $data['data'][$k]['orders']['channel_all']['fail'] = $v2['fail'];
                        $data['data'][$k]['orders']['channel_all']['all_num'] = $v2['all_num'];
                    } else {
                        $data['data'][$k]['orders']['channel_all']['success'] += $v2['success'];
                        $data['data'][$k]['orders']['channel_all']['fail'] += $v2['fail'];
                        $data['data'][$k]['orders']['channel_all']['all_num'] += $v2['all_num'];
                    }
                }
            }
            unset($data['data'][$k]['successStatics']);
        }

        return success('', $data);
    }
}
